﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace laohan.Common.Common
{
    /// <summary>
    /// 常用函数API
    /// </summary>
    public partial class API
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetUID()
        {
            return Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetAppConfigAppSetting(string name)
        {
            string result;

            try
            {
                result = ConfigurationManager.AppSettings[name];
            }
            catch
            {
                throw new Exception(string.Format("获取配置节点信息【{0}】发生错误，请检查配置文件！！！", name));
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void SetAppConfigAppSetting(string name, string value)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                config.AppSettings.Settings[name].Value = value;

                config.Save(ConfigurationSaveMode.Modified);

                ConfigurationManager.RefreshSection("appSettings");
            }
            catch
            {
                throw new Exception(string.Format("配置节点信息【{0}】发生错误，请检查配置文件！！！", name));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetPubConstantString(Assembly assembly, string name)
        {
            return GetAppConfigAppSetting(assembly, name);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetAppConfigAppSetting(Assembly assembly, string name)
        {
            string value;
            try
            {
                ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();
                Uri uri = new Uri(Path.GetDirectoryName(assembly.CodeBase));
                exeConfigurationFileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".dll.config");
                value = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None).AppSettings.Settings[name].Value;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("获取应用程序配置文件【{0}】配置节点信息【{1}】发生错误，错误原因：{2}", assembly.FullName, name, ex.Message));
            }
            return value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetAppConfigAppSetting(string configFullFile, string name)
        {
            try
            {
                string value;

                ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();

                Uri uri = new Uri(Path.GetDirectoryName(configFullFile));

                exeConfigurationFileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, configFullFile);

                value = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None).AppSettings.Settings[name].Value;

                return value;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("获取应用程序配置文件【{0}】配置节点信息【{1}】发生错误，错误原因：{2}", configFullFile, name, ex.Message));
            }
        }

        /// <summary>
        /// 修改配置
        /// </summary>
        /// <param name="configFullFile"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetAppConfigAppSetting(string configFullFile, string key, string value)
        {
            try
            {

                ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();

                Uri uri = new Uri(Path.GetDirectoryName(configFullFile));

                exeConfigurationFileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, configFullFile);

                Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
                configuration.AppSettings.Settings[key].Value = value;

                configuration.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("设置应用程序配置文件【{0}】配置节点信息【{1}】发生错误，错误原因：{2}", configFullFile, key + "+" + value, ex.Message));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="r"></param>
        /// <returns></returns>
        public static T DgRowToEntity<T>(DataGridViewRow r)
        {
            T t = default(T);

            t = Activator.CreateInstance<T>();

            PropertyInfo[] ps = t.GetType().GetProperties();

            foreach (var item in ps)
            {
                if (r.DataGridView.Columns.Contains(item.Name))
                {
                    object v = r.Cells[item.Name].Value;

                    if (v == null || v.GetType() == typeof(System.DBNull))
                    {
                        v = null;
                    }

                    item.SetValue(t, v);
                }
            }
            return t;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetBasePath()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetDirectoryName()
        {
            var dir = new DirectoryInfo(GetBasePath());

            return dir.Name;
        }

        /// <summary>
        /// 应用程序目录信息
        /// </summary>
        /// <returns></returns>
        public static DirectoryInfo AppDirectoryInfo()
        {
            return new DirectoryInfo(GetBasePath());
        }

        /// <summary>
        /// 应用程序父完整名称
        /// </summary>
        /// <returns></returns>
        public static string AppParentFullName()
        {
            return AppDirectoryInfo().Parent.FullName;
        }

        /// <summary>
        /// 多个对象转换成动态数据类型
        /// </summary>
        /// <param name="objects"></param>
        /// <returns></returns>
        public static dynamic ToDynamic(List<object> objects, string[] removeKeys = null)
        {
            try
            {
                IDictionary<string, object> result = new ExpandoObject();

                foreach (var obj in objects)
                {
                    var type = obj.GetType();

                    if (type.Name == "Dictionary`2")
                    {
                        var dict = obj as IDictionary<string, object>;

                        foreach (var key in dict)
                        {
                            result.Add(key.Key, key.Value);
                        }

                        continue;
                    }

                    foreach (PropertyDescriptor pro in TypeDescriptor.GetProperties(obj.GetType()))
                    {
                        var name = pro.Name;
                        var value = pro.GetValue(obj);

                        if (removeKeys != null && ((IList)removeKeys).Contains(name))
                        {
                            continue;
                        }

                        if (result.ContainsKey(name))
                        {
                            continue;
                        }

                        result.Add(name, value);
                    }
                }

                return result as ExpandoObject;
            }
            catch (Exception ex)
            {
                throw new Exception("对象转换成dynamic对象error：" + ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public static dynamic ToDynamic(IDictionary<string, object> dict)
        {
            dynamic result = new ExpandoObject();

            foreach (var entry in dict)
            {
                (result as ICollection<KeyValuePair<string, object>>).Add(new KeyValuePair<string, object>(entry.Key, entry.Value));
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static dynamic ToDynamic(object obj)
        {
            return ToDynamic(new List<object>() { obj });
        }
    }
}